//
//  GLESRenderFrameBuffer.m
//  FrameBufferObject
//
//  Created by 畑圭輔 on 10/03/24.
//  Copyright 2010 Keisuke Hata. All rights reserved.
//

#import "GLESRenderFrameBuffer.h"

#define kIPHONE_WIDTH  320
#define kIPHONE_HEIGHT 480

@implementation GLESRenderFrameBuffer

@synthesize fbo = _fbo;
@synthesize frameBufferTexture = _frameBufferTexture;

- (id) initWithSize : (CGSize)size {
	
	if( self = [super init] ) {
		
		// 指定したサイズのテクスチャを作成
		_frameBufferTexture = [[Texture2D alloc] initWithSize:size];
		if( !_frameBufferTexture ) {
			[self release];
			return nil;
		}
		GLint oldFBO = 0;
		glGetIntegerv(GL_FRAMEBUFFER_BINDING_OES, &oldFBO);

		// FBOを作成
		glGenFramebuffersOES(1, &_fbo);
		glBindFramebufferOES(GL_FRAMEBUFFER_OES, _fbo);
		
		// テクスチャとFBOを結びつける
		glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, _frameBufferTexture.name, 0);
		
		// FBOのステータスをチェックする
		GLuint status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
		if (status != GL_FRAMEBUFFER_COMPLETE_OES)
		{
			[NSException raise:@"FBOTexture" format:@"テクスチャとFBOの関連付けに失敗しました"];
		}
		// 前のFBOに戻す
		glBindFramebufferOES(GL_FRAMEBUFFER_OES, oldFBO);
	}
	return self;
}

- (void) dealloc {

	glDeleteFramebuffersOES(1, &_fbo);
	[_frameBufferTexture release];
	[super dealloc];
}

- (void) clear {

	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glClear( GL_COLOR_BUFFER_BIT );
}

- (void) begin {
	
	glPushMatrix();

	// 以前のFBOを取得
	glGetIntegerv(GL_FRAMEBUFFER_BINDING_OES, &_oldFBO);
	// 作成したFBOにバインド
	glBindFramebufferOES(GL_FRAMEBUFFER_OES, _fbo);
	
	glViewport(0, 0, kIPHONE_WIDTH, kIPHONE_HEIGHT );
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	
	glOrthof( 0, kIPHONE_WIDTH, kIPHONE_HEIGHT, 0, -1, 1 );
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

- (void) end {
	
	// 作成したFBOにバインド
	glBindFramebufferOES(GL_FRAMEBUFFER_OES, _oldFBO);
	glPopMatrix();
}

@end
